package org.zty.util;

import java.text.SimpleDateFormat;
import java.util.HashMap;

import com.fasterxml.jackson.databind.ObjectMapper;





public class Bean2Json {
	public static void main(String[] args) {
		String json="{\"extField\":[{\"aaa\":1},{\"bbb\":2}],\"aaa\":123,\"docTitle\":\"\",\"docType\":\"1\",\"extUrl\":\"\",\"siteId\":\"34\",\"userId\":\"1\",\"userName\":\"admin\",\"subTitle\":\"\",\"auditor\":\"\",\"editor\":\"\",\"author\":\"匿名\",\"docTime\":\"2014-06-16\",\"source\":\"\",\"keyword\":\"\",\"categoryId\":\"25396\",\"extend\":\"\",\"appendixs\":[],\"docCategorys\":[{\"categoryId\":25396,\"docId\":0}],\"docRels\":[],\"htmlContent\":\"\",\"content\":\"\",\"summary\":\"\"}";
		
		
		
//		Map<String,Object> map = (Map<String,Object>)Bean2JSON.toObject("{\"aaa\":\"()_+{}&apos;&quot;;&apos;|+\",\"bbb\":\"432\"}", Map.class);
//		HashMap<String,Object> extField = new HashMap<String,Object>(); 
//		
//		for(String key : map.keySet()){
//			String value = (String)map.get(key);
//			extField.put(key, value);
//			System.out.println(value);
//		}
	}
	public static String toJson(Object o){
		ObjectMapper mapper = null;
		String json = "";
		try {
			mapper = new ObjectMapper();
			json = mapper.writeValueAsString(o);
		} catch (Exception e) {
			mapper = null;
		}finally{
			mapper = null;
		}
		return json;
	}
	public static String toJson(Object o,String dateFormat){
		ObjectMapper mapper = null;
		String json = "";
		try {
			mapper = new ObjectMapper();
			mapper.setDateFormat(new SimpleDateFormat(dateFormat));
			json = mapper.writeValueAsString(o);
		} catch (Exception e) {
			mapper = null;
		}finally{
			mapper = null;
		}
		return json;
	}
	public static Object toObject(String json, Class<?> clazz) {
		ObjectMapper mapper = null;
		Object o = null;
		try {
			mapper = new ObjectMapper();
			o = mapper.readValue(json, clazz);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			mapper = null;
		}
		return o;
	}
	/**
	 * json消息
	 * @param msg 消息内容
	 * @param success  true or false 
	 * @return  string json格式字符串
	 */
	public static String getMsgJson(String msg,boolean success){
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("msg", msg);
		hm.put("rs",success);
		return toJson(hm);
	}
	/**
	 * 获取json对象
	 * @param obj  对象javabean
	 * @param success 操作结果
	 * @return
	 */
	public static String getMsgJson(Object obj,boolean success){
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("obj", obj);
		hm.put("rs",success);
		return toJson(hm);
	}
}
